<?php

namespace app\admin\service;

use app\admin\validate\Login;
use app\common\configs\SettingConf;
use app\common\logic\SmsLogic;
use app\common\model\trAdmin;
use app\common\model\trAdminSession;
use app\saas\model\trMall;
use app\common\model\trResource;
use app\common\model\trSystemSet;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\facade\Validate;

/**
 * Class Auth
 * @package app\admin\service
 * 类
 */
class PasswordService
{
    private $params;
    private $returnData;
    private $mall_id = 0;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    public function sendCode(){
        if(empty($this->params['mobile'])){
            return ErrorCode::code("params_not_exist", "手机号");
        }
        if(!Validate::isMobile($this->params["mobile"])){
            return ErrorCode::code("params_format", "mobile");
        }
        if(!trAdmin::where("mobile", $this->params['mobile'])->count()){
            return ErrorCode::code("customized", "手机号未注册");
        }
        SmsLogic::sendCode($this->params['mobile']);
        $this->returnData["msg"] = "短信发送成功";
        return $this->returnData;
    }

    public function checkVerification(){
        if(empty($this->params['mobile'])){
            return ErrorCode::code("params_not_exist", "手机号");
        }
        if(empty($this->params['code'])){
            return ErrorCode::code("params_not_exist", "验证码");
        }
        if(!SmsLogic::checkValidateCode($this->params['code'], $this->params['mobile'], $msg)){
            return ErrorCode::code("customized", $msg);
        }
        cache($this->params['mobile'], true, 86400);
        return $this->returnData;
    }

    // 修改密码
    public function updatePassword(){
        if(empty($this->params['mobile'])){
            return ErrorCode::code("params_not_exist", "手机号");
        }
        if(empty($this->params['password'])){
            return ErrorCode::code("params_not_exist", "密码");
        }
        if(!cache($this->params['mobile'])){
            return ErrorCode::code("customized", "请先验证短信验证码");
        }
        $admin = trAdmin::where("mobile", $this->params['mobile'])->find();
        if(!$admin){
            return ErrorCode::code("customized", "手机号未注册");
        }
        $admin->password = generate_password($this->params['password'], $admin->salt);
        if(!$admin->save()){
            return ErrorCode::code("customized", "修改失败");
        }
        cache($this->params['mobile'], null);
        return $this->returnData;
    }
}